package com.android.androidbigwork.utils;

import android.util.Log;
import android.widget.ListView;
import androidx.fragment.app.Fragment;
import com.android.androidbigwork.R;
import com.android.androidbigwork.adapter.Demo_List_Adapter;
import com.android.androidbigwork.adapter.MySharesRequestParas;
import com.android.androidbigwork.entity.Item_Share;
import com.android.androidbigwork.entity.RequestParas;
import com.android.androidbigwork.entity.ResultPage;
import com.android.androidbigwork.entity.SharePoto;
import com.google.gson.Gson;
import org.xutils.common.Callback;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


public class MyCallBack implements Callback.CacheCallback<String>{

    private boolean flag = true;

    public void setFlag(boolean f){
        flag = f;
    }

    private Fragment fragment;
    private Demo_List_Adapter demo_list_adapter;

    public MyCallBack( Fragment fragment) {
        this.fragment = fragment;
    }

    public MyCallBack() {
    }

    @Override
    public boolean onCache(String result) {
        return false;
    }

    @Override
    public void onSuccess(String  result) {
        Log.d("", "onSuccess: 请求成功"+result);

        Gson gson = new Gson();
        ResultPage resultPage = gson.fromJson(result, ResultPage.class);
        if(flag)
           RequestParas.pageNum++;
        else
            MySharesRequestParas.pageNum++;

        String[] imgList;
        for (SharePoto sharePoto : resultPage.getContent()) {
            imgList = sharePoto.getPotos().split("&");
            List resultList= new ArrayList<>(Arrays.asList(imgList));

            Item_Share item_share =new Item_Share(sharePoto.getName(),
                    sharePoto.getMessage(),
                    sharePoto.getHeaderPhoto(),
                    resultList
                    );
            demo_list_adapter.add(item_share);
            ListView listView;

            if(flag)
               listView= fragment.getActivity().findViewById(R.id.demoList);
            else
                 listView= fragment.getActivity().findViewById(R.id.MyList);

             listView.setAdapter(demo_list_adapter);

//            listView.setSelected(true);
//            listView.smoothScrollToPosition(demo_list_adapter.getCount()-RequestParas.pageNum);
        }
    }
    @Override
    public void onError(Throwable ex, boolean isOnCallback) {
        Log.d("MyCallBack", " 请求失败");
    }

    @Override
    public void onCancelled(CancelledException cex) {

    }

    @Override
    public void onFinished() {

    }



    public Fragment getFragment() {
        return fragment;
    }

    public void setFragment(Fragment fragment) {
        this.fragment = fragment;
    }

    public Demo_List_Adapter getDemo_list_adapter() {
        return demo_list_adapter;
    }

    public void setDemo_list_adapter(Demo_List_Adapter demo_list_adapter) {
        this.demo_list_adapter = demo_list_adapter;
    }

}
